<template>
  <div class="app-container">
    <!-- 搜索条件区域 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="80px"
    >
      <el-form-item label="仓库编码" prop="warehouseCode">
        <el-input
          v-model="queryParams.warehouseCode"
          placeholder="请输入仓库编码"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="仓库名称" prop="warehouseName">
        <el-input
          v-model="queryParams.warehouseName"
          placeholder="请输入仓库名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="所属公司" prop="companyId">
        <treeselect
          v-model="queryParams.companyId"
          :options="companyOptions"
          :normalizer="normalizer"
          placeholder="请选择所属公司"
          :show-count="true"
          clearable
          style="width: 240px"
        />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
          style="width: 240px"
        >
          <el-option label="启用" value="0" />
          <el-option label="停用" value="1" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['pack:warehouse:add']"
          >新增</el-button
        >
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['pack:warehouse:edit']"
          >修改</el-button
        >
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['pack:warehouse:remove']"
          >删除</el-button
        >
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['pack:warehouse:export']"
          >导出</el-button
        >
      </el-col>



      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table
      v-loading="loading"
      :data="warehouseList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column type="index" label="序号" width="60" align="center" />

      <el-table-column
        label="仓库编码"
        align="left"
        prop="warehouseCode"
        width="120"
        :show-overflow-tooltip="true"
      />

      <el-table-column
        label="仓库名称"
        align="left"
        prop="warehouseName"
        min-width="150"
        :show-overflow-tooltip="true"
      />

      <el-table-column
        label="所属公司"
        align="left"
        width="120"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          {{ getDeptNameById(scope.row.companyId) }}
        </template>
      </el-table-column>

      <el-table-column
        label="所属部门"
        align="left"
        width="120"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          {{ getDeptNameById(scope.row.deptId) }}
        </template>
      </el-table-column>

      <el-table-column
        label="仓库地址"
        align="left"
        prop="warehouseAddress"
        min-width="200"
        :show-overflow-tooltip="true"
      />

      <el-table-column label="管理员" align="center" width="120">
        <template slot-scope="scope">
          <div v-if="scope.row.managerId">
            <div>{{ getUserNameById(scope.row.managerId) }}</div>
            <div class="text-muted" style="font-size: 12px">
              {{ scope.row.managerPhone }}
            </div>
          </div>
          <span v-else class="text-muted">-</span>
        </template>
      </el-table-column>

      <el-table-column label="状态" align="center" width="80">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
            v-hasPermi="['pack:warehouse:edit']"
          ></el-switch>
        </template>
      </el-table-column>

      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="120"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        width="180"
        fixed="right"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
            v-hasPermi="['pack:warehouse:query']"
            >详情</el-button
          >

          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['pack:warehouse:edit']"
            >修改</el-button
          >

          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['pack:warehouse:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增/修改抽屉 -->
    <el-drawer
      :title="title"
      :visible.sync="open"
      direction="rtl"
      size="600px"
      :before-close="cancel"
    >
      <div style="padding: 20px">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="仓库编码" prop="warehouseCode">
                <el-input
                  v-model="form.warehouseCode"
                  placeholder="请输入仓库编码"
                  :disabled="form.warehouseId != null"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="仓库名称" prop="warehouseName">
                <el-input
                  v-model="form.warehouseName"
                  placeholder="请输入仓库名称"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="所属公司" prop="companyId">
                <treeselect
                  v-model="form.companyId"
                  :options="companyOptions"
                  :normalizer="normalizer"
                  placeholder="请选择所属公司"
                  :show-count="true"
                  @input="handleCompanyChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属部门" prop="deptId">
                <treeselect
                  v-model="form.deptId"
                  :options="deptOptions"
                  :normalizer="normalizer"
                  placeholder="请选择所属部门"
                  :show-count="true"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="仓库地址" prop="warehouseAddress">
            <el-input
              v-model="form.warehouseAddress"
              type="textarea"
              :rows="2"
              placeholder="请输入仓库地址"
            />
          </el-form-item>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="管理员姓名" prop="managerId">
                <el-select
                  v-model="form.managerId"
                  placeholder="请选择管理员"
                  clearable
                  filterable
                  @change="handleManagerChange"
                  style="width: 100%"
                >
                  <el-option
                    v-for="user in userOptions"
                    :key="user.userId"
                    :label="user.nickName"
                    :value="user.userId"
                  >
                    <span style="float: left">{{ user.nickName }}</span>
                    <span
                      style="float: right; color: #8492a6; font-size: 13px"
                      >{{ user.userName }}</span
                    >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="管理员电话" prop="managerPhone">
                <el-input
                  v-model="form.managerPhone"
                  placeholder="管理员电话"
                  :disabled="true"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio label="0">启用</el-radio>
              <el-radio label="1">停用</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="form.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注"
            />
          </el-form-item>

          <el-form-item label="电子围栏">
            <MapContainer
              :fence-coordinates="fenceCoordinates"
              :height="'400px'"
              :editable="true"
              @fence-change="handleFenceChange"
            />
            <div style="color: #909399; font-size: 12px; margin-top: 8px">
              <i class="el-icon-info"></i>
              请在地图上设置仓库的电子围栏区域，用于后续的定位和监控功能
            </div>
            
            <!-- 围栏操作状态显示 -->
            <div v-if="showFenceChangeStatus()" class="fence-operations-summary">
              <div class="operations-title">
                <i class="el-icon-warning"></i>
                待执行的围栏操作:
              </div>
              <div v-if="fenceOperations.original.length > 0 && fenceCoordinates.length > 0" class="operation-item change">
                <i class="el-icon-refresh"></i>
                更新围栏: 将替换原有的 {{ fenceOperations.original.length }} 个围栏点
              </div>
              <div v-if="fenceOperations.original.length > 0 && fenceCoordinates.length === 0" class="operation-item delete">
                <i class="el-icon-delete"></i>
                删除围栏: 将删除原有的 {{ fenceOperations.original.length }} 个围栏点
              </div>
              <div v-if="fenceOperations.original.length === 0 && fenceCoordinates.length > 0" class="operation-item add">
                <i class="el-icon-plus"></i>
                新增围栏: {{ fenceCoordinates.length }} 个围栏点
              </div>
              <div class="operation-note">
                点击"确定"按钮时将在数据库事务中执行以上操作
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>

      <div
        style="padding: 20px; text-align: right; border-top: 1px solid #e8e8e8"
      >
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-drawer>

    <!-- 详情抽屉 -->
    <el-drawer
      title="仓库详情"
      :visible.sync="detailOpen"
      direction="rtl"
      size="600px"
    >
      <div style="padding: 20px">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="仓库编码">
            {{ detailData.warehouseCode }}
          </el-descriptions-item>
          <el-descriptions-item label="仓库名称">
            {{ detailData.warehouseName }}
          </el-descriptions-item>
          <el-descriptions-item label="所属公司">
            {{ getDeptNameById(detailData.companyId) }}
          </el-descriptions-item>
          <el-descriptions-item label="所属部门">
            {{ getDeptNameById(detailData.deptId) || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="仓库地址" :span="2">
            {{ detailData.warehouseAddress || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="管理员姓名">
            {{ getUserNameById(detailData.managerId) }}
          </el-descriptions-item>
          <el-descriptions-item label="管理员电话">
            {{ detailData.managerPhone || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="detailData.status === '0' ? 'success' : 'danger'">
              {{ detailData.status === "0" ? "启用" : "停用" }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ parseTime(detailData.createTime, "{y}-{m}-{d} {h}:{i}:{s}") }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间">
            {{ parseTime(detailData.updateTime, "{y}-{m}-{d} {h}:{i}:{s}") }}
          </el-descriptions-item>
          <el-descriptions-item label="创建者">
            {{ detailData.createBy }}
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">
            {{ detailData.remark || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="电子围栏" :span="2">
            <div v-if="getDetailFenceCoordinates().length > 0">
              <MapContainer
                :fence-coordinates="getDetailFenceCoordinates()"
                :height="'300px'"
                :editable="false"
                :show-fullscreen="true"
              />
            </div>
            <span v-else class="text-muted">未设置电子围栏</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {
  listWarehouse,
  getWarehouse,
  delWarehouse,
  addWarehouse,
  updateWarehouse,
} from "@/api/pack/warehouse";
import { getWarehouseFence } from "@/api/pack/warehouseFence";
import { listDept } from "@/api/system/dept";
import { listUser } from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import MapContainer from "@/components/MapContainer";

export default {
  name: "Warehouse",
  components: { Treeselect, MapContainer },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 仓库表格数据
      warehouseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示详情弹出层
      detailOpen: false,
      // 详情数据
      detailData: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        warehouseCode: null,
        warehouseName: null,
        companyId: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 围栏坐标数据
      fenceCoordinates: [],
      // 围栏操作记录（用于跟踪新增、删除操作）
      fenceOperations: {
        original: []  // 原始围栏数据（用于对比）
      },
      // 表单校验
      rules: {
        warehouseCode: [
          { required: true, message: "仓库编码不能为空", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "仓库编码长度在1到50个字符",
            trigger: "blur",
          },
          {
            pattern: /^[A-Z0-9]+$/,
            message: "仓库编码只能包含大写字母和数字",
            trigger: "blur",
          },
        ],
        warehouseName: [
          { required: true, message: "仓库名称不能为空", trigger: "blur" },
          {
            min: 1,
            max: 100,
            message: "仓库名称长度在1到100个字符",
            trigger: "blur",
          },
        ],
        companyId: [
          { required: true, message: "所属公司不能为空", trigger: "change" },
        ],
        warehouseAddress: [
          {
            max: 500,
            message: "仓库地址长度不能超过500个字符",
            trigger: "blur",
          },
        ],
      },
      // 公司选项
      companyOptions: [],
      // 部门选项
      deptOptions: [],
      // 完整的部门树数据（用于名称匹配）
      allDeptList: [],
      // 用户选项
      userOptions: [],
    };
  },
  created() {
    this.getList();
    this.loadCompanyOptions();
    this.loadUserOptions();
  },
  methods: {
    /** 查询仓库列表 */
    getList() {
      this.loading = true;
      listWarehouse(this.queryParams).then((response) => {
        this.warehouseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        warehouseId: null,
        warehouseCode: null,
        warehouseName: null,
        companyId: null,
        deptId: null,
        warehouseAddress: null,
        managerId: null,
        managerPhone: null,
        status: "0",
        remark: null,
        fenceCoordinates: null,
      };
      // 重置围栏坐标
      this.fenceCoordinates = [];
      // 重置围栏操作记录
      this.fenceOperations = {
        original: []
      };
      // 清空部门选项
      this.deptOptions = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.warehouseId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // 确保新增时围栏坐标为空
      this.fenceCoordinates = [];
      this.open = true;
      this.title = "添加仓库";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const warehouseId = row.warehouseId || this.ids;
      getWarehouse(warehouseId).then((response) => {
        this.form = response.data;
        
        // 从围栏接口获取完整的围栏数据（包含ID等信息）
        getWarehouseFence(warehouseId).then((res) => {
          console.log('围栏接口返回数据:', res);
          if (res && res.data) {
            let originalFenceRecords = [];
            let coordinatesForDisplay = [];
            
            // 如果返回的是围栏记录数组
            if (Array.isArray(res.data)) {
              originalFenceRecords = res.data;
              // 按点序号排序并组织成坐标数组
              coordinatesForDisplay = this.convertFenceRecordsToCoordinates(res.data);
            } else if (res.data.list && Array.isArray(res.data.list)) {
              // 处理分页返回的数据格式
              originalFenceRecords = res.data.list;
              coordinatesForDisplay = this.convertFenceRecordsToCoordinates(res.data.list);
            } else if (res.data.coordinates) {
              // 如果返回的是单个围栏对象
              originalFenceRecords = [res.data];
              coordinatesForDisplay = this.parseFenceCoordinates(res.data.coordinates);
            } else {
              // 如果只是坐标数据
              coordinatesForDisplay = this.parseFenceCoordinates(res.data);
            }
            
            // 加载围栏数据到地图组件，同时设置原始数据
            this.loadFenceCoordinates(coordinatesForDisplay, originalFenceRecords);
          } else {
            // 如果围栏接口没有数据，清空围栏
            this.loadFenceCoordinates([]);
          }
        }).catch((error) => {
          console.warn('获取围栏数据失败:', error);
          // 如果围栏接口失败，清空围栏
          this.loadFenceCoordinates([]);
        });
        
        this.open = true;
        this.title = "修改仓库";
        // 确保部门数据已加载，然后加载对应公司的部门选项
        this.ensureDeptDataLoaded().then(() => {
          if (this.form.companyId) {
            this.loadDeptOptions(this.form.companyId);
          }
        });
      });
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      const warehouseId = row.warehouseId;
      getWarehouse(warehouseId).then((response) => {
        this.detailData = response.data;
        
        // 获取围栏数据用于详情显示
        getWarehouseFence(warehouseId).then((res) => {
          if (res && res.data && Array.isArray(res.data)) {
            // 转换围栏记录为坐标格式
            const fenceCoordinates = this.convertFenceRecordsToCoordinates(res.data);
            this.detailData.fenceCoordinates = fenceCoordinates;
          } else {
            this.detailData.fenceCoordinates = [];
          }
        }).catch((error) => {
          console.warn('获取详情围栏数据失败:', error);
          this.detailData.fenceCoordinates = [];
        }).finally(() => {
          this.detailOpen = true;
        });
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          const formData = { ...this.form };
          
          if (this.form.warehouseId != null) {
            // 修改仓库 - 构建围栏操作DTO格式
            this.prepareUpdateWarehouseData(formData);
          } else {
            // 新增仓库 - 构建围栏信息DTO格式
            this.prepareAddWarehouseData(formData);
          }
        }
      });
    },

    /** 准备新增仓库数据 - 构建围栏信息DTO格式 */
    prepareAddWarehouseData(formData) {
      // 清理不需要的字段
      delete formData.fenceCoordinates;
      
      // 如果有围栏坐标，构建fenceList
      if (this.fenceCoordinates && this.fenceCoordinates.length > 0) {
        formData.fenceList = [{
          fenceType: "1", // 多边形围栏
          points: this.fenceCoordinates.map((coord, index) => {
            // 处理不同的坐标格式
            let lat, lng;
            if (Array.isArray(coord)) {
              // 数组格式 [lng, lat]
              lng = coord[0];
              lat = coord[1];
            } else if (coord && typeof coord === 'object') {
              // 对象格式 {lat: x, lng: x} 或 {latitude: x, longitude: x}
              lat = coord.lat || coord.latitude;
              lng = coord.lng || coord.longitude;
            } else {
              console.warn('无效的坐标格式:', coord);
              return null;
            }
            
            return {
              pointOrder: index + 1,
              latitude: lat,
              longitude: lng
            };
          }).filter(point => point !== null) // 过滤掉无效的坐标
        }];
        
        console.log('构建的围栏数据:', formData.fenceList);
      }
      
      console.log('新增仓库数据:', formData);
      
      addWarehouse(formData).then((response) => {
        console.log('新增仓库响应:', response);
        if (response.data && response.data.fenceIds) {
          this.$modal.msgSuccess(`新增成功，创建了 ${response.data.fenceIds.length} 个围栏点`);
        } else {
          this.$modal.msgSuccess("新增成功");
        }
        this.open = false;
        this.getList();
      }).catch((error) => {
        console.error('新增仓库失败:', error);
        this.$modal.msgError("新增失败");
      });
    },

    /** 准备更新仓库数据 - 构建围栏操作DTO格式 */
    prepareUpdateWarehouseData(formData) {
      // 清理不需要的字段
      delete formData.fenceCoordinates;
      
      // 构建围栏操作列表
      const fenceOperations = [];
      
      // 1. 如果有原始围栏数据且当前有新围栏，则需要删除原有的
      if (this.fenceOperations.original.length > 0 && this.fenceCoordinates.length > 0) {
        // 删除所有原有围栏
        this.fenceOperations.original.forEach(originalFence => {
          if (originalFence.id || originalFence.fenceId) {
            fenceOperations.push({
              operationType: "delete",
              fenceId: originalFence.id || originalFence.fenceId
            });
          }
        });
      }
      
      // 2. 如果当前有围栏坐标，则新增围栏
      if (this.fenceCoordinates && this.fenceCoordinates.length > 0) {
        fenceOperations.push({
          operationType: "create",
          fenceType: "1", // 多边形围栏
          points: this.fenceCoordinates.map((coord, index) => {
            // 处理不同的坐标格式
            let lat, lng;
            if (Array.isArray(coord)) {
              // 数组格式 [lng, lat]
              lng = coord[0];
              lat = coord[1];
            } else if (coord && typeof coord === 'object') {
              // 对象格式 {lat: x, lng: x} 或 {latitude: x, longitude: x}
              lat = coord.lat || coord.latitude;
              lng = coord.lng || coord.longitude;
            } else {
              console.warn('无效的坐标格式:', coord);
              return null;
            }
            
            return {
              pointOrder: index + 1,
              latitude: lat,
              longitude: lng
            };
          }).filter(point => point !== null) // 过滤掉无效的坐标
        });
      } else if (this.fenceOperations.original.length > 0) {
        // 3. 如果没有新围栏但有原始围栏，则删除所有原始围栏
        this.fenceOperations.original.forEach(originalFence => {
          if (originalFence.id || originalFence.fenceId) {
            fenceOperations.push({
              operationType: "delete",
              fenceId: originalFence.id || originalFence.fenceId
            });
          }
        });
      }
      
      // 添加围栏操作到表单数据
      if (fenceOperations.length > 0) {
        formData.fenceOperations = fenceOperations;
      }
      
      console.log('更新仓库数据:', formData);
      
      updateWarehouse(formData).then((response) => {
        console.log('更新仓库响应:', response);
        
        let successMsg = "修改成功";
        if (response.data && response.data.fenceOperationResults) {
          const results = response.data.fenceOperationResults;
          const successCount = results.filter(r => r.success).length;
          const failCount = results.filter(r => !r.success).length;
          
          if (failCount > 0) {
            const failedMessages = results
              .filter(r => !r.success)
              .map(r => r.message)
              .join('; ');
            this.$modal.msgWarning(`修改完成，但有 ${failCount} 个围栏操作失败: ${failedMessages}`);
          } else {
            successMsg = `修改成功，完成了 ${successCount} 个围栏操作`;
          }
        }
        
        this.$modal.msgSuccess(successMsg);
        this.open = false;
        this.getList();
      }).catch((error) => {
        console.error('更新仓库失败:', error);
        this.$modal.msgError("修改失败，请检查数据完整性");
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const warehouseIds = row.warehouseId || this.ids;
      this.$modal
        .confirm('是否确认删除仓库编号为"' + warehouseIds + '"的数据项？')
        .then(function () {
          return delWarehouse(warehouseIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "pack/warehouse/export",
        {
          ...this.queryParams,
        },
        `warehouse_${new Date().getTime()}.xlsx`
      );
    },
    /** 状态修改 */
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal
        .confirm('确认要"' + text + '""' + row.warehouseName + '"仓库吗？')
        .then(function () {
          return updateWarehouse(row);
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.status = row.status === "0" ? "1" : "0";
        });
    },

    /** 加载公司选项 */
    loadCompanyOptions() {
      return listDept().then((response) => {
        // 保存完整的部门数据用于名称匹配
        this.allDeptList = this.handleTree(response.data, "deptId", "parentId");
        // 设置公司选项
        this.companyOptions = this.allDeptList;
      });
    },
    /** 确保部门数据已加载 */
    ensureDeptDataLoaded() {
      if (this.allDeptList && this.allDeptList.length > 0) {
        // 数据已加载，直接返回resolved promise
        return Promise.resolve();
      } else {
        // 数据未加载，重新加载
        return this.loadCompanyOptions();
      }
    },
    /** 加载部门选项 */
    loadDeptOptions(companyId) {
      // 从完整的部门树中筛选指定公司下的部门
      const filterDeptByCompany = (deptList, targetCompanyId) => {
        for (let dept of deptList) {
          if (dept.deptId === targetCompanyId) {
            return dept.children || [];
          }
          if (dept.children && dept.children.length > 0) {
            const result = filterDeptByCompany(dept.children, targetCompanyId);
            if (result.length > 0) return result;
          }
        }
        return [];
      };

      this.deptOptions = filterDeptByCompany(this.allDeptList, companyId);
    },
    /** 公司变化时更新部门选项 */
    handleCompanyChange(companyId) {
      // 清空当前选中的部门
      this.form.deptId = null;
      // 清空部门选项
      this.deptOptions = [];
      // 如果选择了公司，则加载对应的部门选项
      if (companyId) {
        // 确保部门数据已加载
        this.ensureDeptDataLoaded().then(() => {
          this.loadDeptOptions(companyId);
        });
      }
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children,
      };
    },
    /** 根据部门ID获取部门名称 */
    getDeptNameById(deptId) {
      if (!deptId) return "-";

      // 在完整的部门树中查找
      const findDeptName = (deptList, targetId) => {
        for (let dept of deptList) {
          if (dept.deptId === targetId) {
            return dept.deptName;
          }
          if (dept.children && dept.children.length > 0) {
            const result = findDeptName(dept.children, targetId);
            if (result) return result;
          }
        }
        return null;
      };

      return findDeptName(this.allDeptList, deptId) || "-";
    },
    /** 加载用户选项 */
    loadUserOptions() {
      listUser({ status: "0" }).then((response) => {
        this.userOptions = response.rows || [];
      });
    },
    /** 管理员选择变化处理 */
    handleManagerChange(userId) {
      if (!userId) {
        this.form.managerPhone = null;
        return;
      }

      // 根据选中的用户ID找到对应的用户信息
      const selectedUser = this.userOptions.find(
        (user) => user.userId === userId
      );
      if (selectedUser) {
        this.form.managerPhone = selectedUser.phonenumber || "";
      }
    },
    /** 根据用户ID获取用户姓名 */
    getUserNameById(userId) {
      if (!userId) return "-";
      const user = this.userOptions.find((u) => u.userId === userId);
      return user ? user.nickName : "-";
    },

    /** 处理围栏变更 */
    handleFenceChange(event) {
      this.fenceCoordinates = event.coordinates;
      console.log("围栏坐标已更新:", this.fenceCoordinates);
      console.log("坐标数据格式检查:", this.fenceCoordinates.length > 0 ? this.fenceCoordinates[0] : '无数据');
      
      // 处理围栏增量更新逻辑
      this.processFenceOperations(event.coordinates);
    },

    /** 处理围栏操作（增量更新） */
    processFenceOperations(newCoordinates) {
      // 简化围栏操作逻辑，只记录当前坐标和原始数据的变化状态
      const hasOriginalFence = this.fenceOperations.original.length > 0;
      const hasNewFence = newCoordinates && newCoordinates.length > 0;
      
      console.log('围栏变更状态:', {
        hasOriginalFence,
        hasNewFence,
        originalCount: this.fenceOperations.original.length,
        newCoordinatesCount: newCoordinates ? newCoordinates.length : 0
      });
    },

    /** 解析围栏坐标数据 */
    parseFenceCoordinates(coordinatesData) {
      if (!coordinatesData) return [];

      try {
        // 如果是字符串，尝试解析JSON
        if (typeof coordinatesData === "string") {
          const parsed = JSON.parse(coordinatesData);
          return Array.isArray(parsed) ? parsed : [];
        }
        
        // 如果是数组，直接返回
        if (Array.isArray(coordinatesData)) {
          return coordinatesData;
        }
        
        // 如果是对象，可能包含coordinates字段
        if (typeof coordinatesData === "object" && coordinatesData.coordinates) {
          return this.parseFenceCoordinates(coordinatesData.coordinates);
        }
        
        return [];
      } catch (error) {
        console.warn("围栏坐标解析失败:", error, coordinatesData);
        return [];
      }
    },

    /** 加载围栏坐标数据 */
    loadFenceCoordinates(coordinatesData, originalFenceData = null) {
      const coordinates = this.parseFenceCoordinates(coordinatesData);
      
      // 验证坐标数据有效性
      const validCoordinates = coordinates.filter(coord => {
        if (!Array.isArray(coord) || coord.length !== 2) return false;
        const [lng, lat] = coord;
        // 检查是否为有效坐标：不是NaN，不是0，且在合理范围内
        if (isNaN(lng) || isNaN(lat) || lng === 0 || lat === 0) return false;
        if (lat < -90 || lat > 90 || lng < -180 || lng > 180) return false;
        return true;
      });
      
      this.fenceCoordinates = validCoordinates;
      
      // 设置原始围栏数据（用于跟踪变更）
      if (originalFenceData && Array.isArray(originalFenceData)) {
        this.fenceOperations.original = originalFenceData;
      } else if (validCoordinates.length > 0) {
        // 如果没有提供原始数据，则根据坐标生成默认记录
        this.fenceOperations.original = [{
          id: null, // 新增时没有ID
          warehouseId: this.form.warehouseId,
          coordinates: JSON.stringify(validCoordinates)
        }];
      } else {
        this.fenceOperations.original = [];
      }
      
      console.log("原始坐标数据:", coordinates);
      console.log("有效围栏坐标:", validCoordinates);
      console.log("原始围栏数据:", this.fenceOperations.original);
      
      if (validCoordinates.length === 0 && coordinates.length > 0) {
        console.warn("所有围栏坐标都无效，将显示默认北京位置");
      }
    },

    /** 将后台围栏记录转换为地图坐标格式 */
    convertFenceRecordsToCoordinates(fenceRecords) {
      if (!fenceRecords || !Array.isArray(fenceRecords)) {
        return [];
      }
      
      // 按点序号排序并转换为坐标格式
      const sortedRecords = fenceRecords.sort((a, b) => (a.pointOrder || 0) - (b.pointOrder || 0));
      
      // 返回地图组件期望的 [lng, lat] 数组格式
      return sortedRecords.map(record => {
        const lat = parseFloat(record.latitude);
        const lng = parseFloat(record.longitude);
        // 检查是否为有效坐标：不是NaN，不是0，且在合理范围内
        if (isNaN(lat) || isNaN(lng) || lat === 0 || lng === 0) {
          return null;
        }
        // 经纬度范围检查
        if (lat < -90 || lat > 90 || lng < -180 || lng > 180) {
          return null;
        }
        return [lng, lat]; // 地图组件期望的格式
      }).filter(coord => coord !== null);
    },

    /** 判断是否显示围栏变更状态 */
    showFenceChangeStatus() {
      // 如果是新增仓库，则只有当有围栏时才显示
      if (!this.form.warehouseId) {
        return this.fenceCoordinates && this.fenceCoordinates.length > 0;
      }
      
      // 如果是修改仓库，检查围栏是否有变化
      const hasOriginal = this.fenceOperations.original.length > 0;
      const hasCurrent = this.fenceCoordinates && this.fenceCoordinates.length > 0;
      
      // 有原始围栏但当前无围栏（删除操作）
      if (hasOriginal && !hasCurrent) return true;
      
      // 无原始围栏但当前有围栏（新增操作）
      if (!hasOriginal && hasCurrent) return true;
      
      // 都有围栏，检查是否有变化（更新操作）
      if (hasOriginal && hasCurrent) {
        // 简单比较数量，实际应用中可以做更精确的比较
        return this.fenceOperations.original.length !== this.fenceCoordinates.length;
      }
      
      return false;
    },

    /** 获取详情页面的围栏坐标 */
    getDetailFenceCoordinates() {
      // 直接返回详情数据中的围栏坐标（已经转换为正确格式）
      if (this.detailData && this.detailData.fenceCoordinates) {
        return Array.isArray(this.detailData.fenceCoordinates) ? this.detailData.fenceCoordinates : [];
      }
      return [];
    },
  },
};
</script>

<style scoped>
.text-muted {
  color: #999;
}

/* 围栏操作状态显示样式 */
.fence-operations-summary {
  margin-top: 12px;
  padding: 12px;
  background: #fdf6ec;
  border: 1px solid #faecd8;
  border-radius: 4px;
  font-size: 12px;
}

.operations-title {
  color: #e6a23c;
  font-weight: 500;
  margin-bottom: 8px;
}

.operations-title i {
  margin-right: 4px;
}

.operation-item {
  margin: 4px 0;
  display: flex;
  align-items: center;
}

.operation-item i {
  margin-right: 6px;
  width: 14px;
}

.operation-item.delete {
  color: #f56c6c;
}

.operation-item.add {
  color: #67c23a;
}

.operation-item.change {
  color: #409eff;
}

.operation-note {
  margin-top: 8px;
  color: #909399;
  font-style: italic;
  font-size: 11px;
}
</style>
